import React, { forwardRef, useEffect } from "react";
import { Form, Input, Select } from "antd";

const { Option } = Select;

const UserForm = forwardRef(({ roles, user = {} }, ref) => {
  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue(user);
  }, [user, form]);

  useEffect(() => {
    ref.current = form;
  }, [form, ref]);

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 15 },
  };

  const prefixSelector = (
    <Form.Item name="prefix" initialValue="86" noStyle>
      <Select style={{ width: 70 }}>
        <Option value="86">+86</Option>
        <Option value="87">+87</Option>
      </Select>
    </Form.Item>
  );

  return (
    <Form form={form} {...formItemLayout}>
      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <Input placeholder="请输入用户名" />
      </Form.Item>
      {!user._id && (
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>
      )}
      <Form.Item
        label="手机号"
        name="phone"
        rules={[{ required: true, message: "请输入正确的手机号码" }]}
      >
        <Input
          addonBefore={prefixSelector}
          style={{ width: "100%" }}
          placeholder="请输入手机号"
        />
      </Form.Item>
      <Form.Item
        label="邮箱"
        name="email"
        rules={[
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: "邮箱格式不正确",
          },
        ]}
      >
        <Input placeholder="请输入邮箱" />
      </Form.Item>
      <Form.Item
        label="角色"
        name="role_id"
        rules={[{ required: true, message: "必须指定角色" }]}
      >
        <Select>
          {roles.map((role) => (
            <Option key={role._id} value={role._id}>
              {role.name}
            </Option>
          ))}
        </Select>
      </Form.Item>
    </Form>
  );
});

export default UserForm;
